import csp from './CSPUtils.js';
import parse from './parseGoods.js';
var is_address_update = false;

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    // let isAsync = false;
    switch (message.greeting) {
        case 'nowAccount': // 个人中心页面记录当前登录得账号
            csp.nowAccount(message);
            break;
        case 'login':
            // csp.login(message, sender, sendResponse);
            break;
        case 'getSku': // 采集商品信息
            csp.getSku(message, sender, sendResponse);
            // sendResponse();
            break;
        case 'getSkuByDOM':
            csp.getSkuByDOM(message, sender, sendResponse);
            break;
        case 'autoSendOrder': // 采集待收货订单
            csp.autoSendOrder(message, sender, sendResponse);
            break;
        case 'handOrder': // 手动下单
            csp.handOrder(message, sender, sendResponse);
            break;
        case 'fetchAddress':
            csp.fetchAddress(message, sender, sendResponse);
            break;
        case 'showPurchaseOrder':
            csp.showPurchaseOrder(message, sender, sendResponse);
            break;
        case 'orderSnAsync':
            csp.orderSnAsync(message, sender, sendResponse);
            break;
        case 'addAccount':
            csp.addAccount(message, sender, sendResponse);
            break;
        case 'setAccount':
            csp.setAccount(message, sender, sendResponse);
            break;
        case 'autoOrder':
            csp.autoOrder(message, sender, sendResponse);
            break;
        case 'autoPay':
            csp.autoPay(message, sender, sendResponse);
            break;
        case 'savePay':
            csp.savePay(message, sender, sendResponse);
            break;
        case 'closeAuto':
            //关闭自动下单
            csp.closeAuto(message, sender, sendResponse);
            break;
        case 'startAuto':
            csp.startAuto(message, sender, sendResponse);
            break;
        case 'closeAutoSend':
            csp.closeAutoSend(message, sender, sendResponse);
            break;
        case 'startAutoSend':
            csp.startAutoSend(message, sender, sendResponse);
            break;
        case 'stopAutoSend':
            csp.stopAutoSend(message, sender, sendResponse);
            break;
        case 'payFinish':
            // 检查
            csp.payFinish(message, sender, sendResponse);
            break;
        case 'checkShip':
            csp.checkShip(message, sender, sendResponse);
            break;
        case 'refundShip':
            csp.refundShip(message, sender, sendResponse);
            break;
        case 'afterSaleHand':
            csp.afterSaleHand(message, sender, sendResponse);
            break;
        case 'afterSaleDetail':
            csp.afterSaleDetail(message, sender, sendResponse);
            break;
        case 'autoAfter':
            csp.autoAfter(message, sender, sendResponse);
            break;
        case 'autoAfterClose':
            csp.autoAfterClose(message, sender, sendResponse);
            break;
        case 'closePDDOrder':
            csp.closePDDOrder(message, sender, sendResponse);
            break;
        case 'orderMall':
            csp.orderMall(message, sender, sendResponse);
            break;
        case 'searchResult':
            parse.searchResult(message, sender, sendResponse);
            break;
        case 'autoorderClear':
            csp.autoorderClear(message, sender, sendResponse);
            break;
        default:
            break;
    }
    // sendResponse();
    return true;

});


chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
        // 提取 apptoken 和 user-agent
        const authHeader = details.requestHeaders.find(header => 
            header.name.toLowerCase() === 'apptoken'
        );
        const agent = details.requestHeaders.find(header=> 
            header.name.toLowerCase() === 'user-agent'
        );
        if (authHeader) {
            chrome.storage.local.set({apptoken: authHeader.value})
        }
        if (agent) {
            chrome.storage.local.set({agent: agent.value})
        }
    },
    { urls: ["<all_urls>"] },
    ["requestHeaders"]
);

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {        
        if (details.url.includes('/proxy/api/order/prepay')) {
            var { method, url, requestBody } = details;
            var rawPayload = new TextDecoder().decode(
              requestBody.raw[0].bytes
            );

            var originalData = JSON.parse(rawPayload);
            csp.orderSnBind(originalData.order_sn)
        }

        if (details.url.includes('https://mobile.yangkeduo.com/proxy/api/api/van-spike/prepay')) {
            var { method, url, requestBody } = details;
            var rawPayload = new TextDecoder().decode(
              requestBody.raw[0].bytes
            );

            var originalData = JSON.parse(rawPayload);
            csp.orderSnBind(originalData.order_sn)
        }
        

        if (details.url.indexOf('/proxy/api/after_sales/create') != -1) {
            console.log('售后了')
            var { method, url, requestBody } = details;
            var rawPayload = new TextDecoder().decode(
              requestBody.raw[0].bytes
            );

            var originalData = JSON.parse(rawPayload);
            //解析完成
            //同步一下订单
            var new_message = {
                orderSn: originalData.order_sn,
                refund_amount: originalData.refund_amount,
                question_desc: originalData.question_desc,
                autoType: 'check',
            };
            var sender = {
                tab: {id: 0}
            };
            var sendResponse = {};
            //等待2-3秒
            setTimeout(function () {
                csp.orderSnAsync(new_message, sender, sendResponse);
            }, 2500);
            
            // csp.orderSnBind(originalData.order_sn);
        }

        if (details.url.indexOf('https://mobile.yangkeduo.com/proxy/api/after_sales/confirm_delivery') != -1) {
            console.log('填单号了');
            var { method, url, requestBody } = details;
            var rawPayload = new TextDecoder().decode(
              requestBody.raw[0].bytes
            );

            var originalData = JSON.parse(rawPayload);

            var reqData = {
                aftersale_id: originalData.aftersale_id,
                tracking_number: originalData.tracking_number,
                shipping_name: originalData.shipping_name,
            }
            csp.sendApi('/chrome/after/tracking_number', reqData);
        }

        // 页面经过首页搜索 商品页面时 清除缓存的order_id 以免下单混乱 
        const urlObj = new URL(details.url);
        urlObj.search = ''; 
        const urlWithoutQuery = urlObj.toString();
        if (urlWithoutQuery == 'https://mobile.yangkeduo.com/' || urlWithoutQuery == 'https://mobile.yangkeduo.com' || urlWithoutQuery == 'https://mobile.yangkeduo.com/personal.html') {
            // 清除 下单缓存
            csp.StorageSetPromise('platform_order_id', 0);
        }
        return {};  // 不能阻塞
    },
    { urls: ["<all_urls>"] },
    ["requestBody"]
);

chrome.tabs.onRemoved.addListener((tabId) => {
    chrome.storage.local.get('erptabid', function(result) {
        if (tabId == result.erptabid) {
            chrome.runtime.sendMessage({greeting: 'closeAuto'});
        }
    });

    chrome.storage.local.get('hand_order_tab', function(result) {
        // 检测是否是多开检测页面关闭了
        if (tabId == result.hand_order_tab) {
            chrome.storage.local.set({hand_order_tab: ''});
        }
    });
});

// cookie变化时
// chrome.cookies.onChanged.addListener(async (changeInfo) => {
//     // changeInfo.cause === "explicit" 插件修改   overwrite 覆盖修改
//     if (changeInfo.cause == 'explicit') {
//         return;
//     }

//     var cookies = await new Promise((resolve) => {
//         chrome.cookies.getAll({
//             url:  "https://mobile.yangkeduo.com",
//         }, resolve);
//     });
//     chrome.storage.local.set({cookies: cookies});
//     return {};

// });


// 监听所有网络请求
// chrome.debugger.onEvent.addListener((source, method, params) => {
//     if (method === "Network.requestWillBeSent") {
//         return;
//     }

//     if (method === "Network.responseReceived") {
//         if (params.response.url.indexOf("https://mobile.yangkeduo.com/proxy/api/search") == -1) {
//             return;
//         }
//         chrome.debugger.sendCommand(
//             {tabId: source.tabId},
//             'Network.getResponseBody',
//             {requestId: params.requestId},
//             (response) => {
//                 // console.log(params.response.url);
//                 var body = JSON.parse(response.body);
//                 console.log(body.items);
//                 parse.searchNet(body.items, source.tabId);
//             }
//         );
//     }
// });